package com.example.springpostbody.core.interceptor;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.example.springpostbody.core.CustomRequestWrapper;
import com.example.springpostbody.core.PropertyAppender;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Nullable;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

@Component
public class PostRequestInterceptor implements HandlerInterceptor {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler) throws Exception {

        // 正确使用 RepeatableRequestWrapper 包装请求
        if (request instanceof CustomRequestWrapper) {
            request = new CustomRequestWrapper(request);

            String jsonStr = ((CustomRequestWrapper) request).getBody();
            System.out.println("PostRequestInterceptor --> 拦截器="+jsonStr);

            //判断当前拦截到的是Controller的方法还是其他资源
            if (!(handler instanceof HandlerMethod)) {
                //当前拦截到的不是动态方法（控制器中的方法），直接放行
                return true;
            }
            //获取访问的方法
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //如果没有被日志注解注解，则放行
        /*if (!method.isAnnotationPresent(Logger.class)) {
            return true;
        }*/

            // 反编译一个类的方法
            StringBuilder s = new StringBuilder();
            Parameter[] methodParameters = method.getParameters();


            for(Parameter item : methodParameters){
                Object anyObj = JSON.parseObject(jsonStr,item.getType());
                System.out.println(item.getType().getSimpleName());
                if ("TestVo".equals(item.getType().getSimpleName())) {
                    //List<Map<String,Object>> list2 = JSON.parseObject(jsonString,new TypeReference<List<Map<String,Object>>>(){});
                    //Map<String,Object> map = JSON.parseObject(jsonStr, Map.class);
                    Map<String,Object> map = JSON.parseObject(jsonStr, new TypeReference<>() {});
                    System.out.println("PostRequestInterceptor --> Map对象="+JSON.toJSONString(map));
                }
                Class<?> clazz = anyObj.getClass();
                /*
                Method[] methods = clazz.getDeclaredMethods();
                for(Method methodItem : methods){
                    // 参数列表
                    Class[] parameterTypes = method.getParameterTypes();
                    for(Class parameterType : parameterTypes){
                        s.append(parameterType.getSimpleName());
                        s.append(",");
                    }

                    // 获取修饰符列表
                    System.out.println(Modifier.toString(method.getModifiers()));
                    // 获取方法的返回值类型
                    System.out.println(method.getReturnType().getSimpleName());
                    // 获取方法名
                    System.out.println(method.getName());
                    // 方法的修饰符列表（一个方法的参数可能会有多个。）
                    Class[] parameterTypes = method.getParameterTypes();
                    for(Class parameterType : parameterTypes){
                        System.out.println(parameterType.getSimpleName());
                    }
                }*/

                /*Class stringClass = Class.forName("java.lang.String");
                // 获取String的父类
                Class superClass = stringClass.getSuperclass();
                System.out.println(superClass.getName());
                // 获取String类实现的所有接口（一个类可以实现多个接口。）
                Class[] interfaces = stringClass.getInterfaces();
                for(Class in : interfaces){
                    System.out.println(in.getName());
                }*/

                //无参
                /*Constructor<?> constructor = clazz.getDeclaredConstructor();
                Object o = constructor.newInstance();*/

                // 调用有参构造
                /*Constructor<?> constructor1 = clazz.getDeclaredConstructor(Integer.class, String.class);
                Object o1 = constructor1.newInstance(100, "zhangsan");*/



                /*Field newField = clazz.getDeclaredField("ext");
                newField.setAccessible(true);
                newField.set(anyObj, "扩展字段");*/

                Map<String, Object> propertiesMap = new HashMap<>(1);
                propertiesMap.put("age", 18);

                //Object obj = PropertyAppender.generate(anyObj, propertiesMap);

                // 调用方法
                /*Method login = clazz.getDeclaredMethod("login", String.class, String.class);
                Object retValue = login.invoke(anyObj, "zhangsan", "123456");*/
                //System.err.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
                //System.err.println(JSON.toJSONString(obj));
            }
        }


        //其他无关校验逻辑和其他信息(略)
        //String requestBody = ((CustomHttpRequestWrapper) request);
        //System.out.println(requestBody);
        //3.记录方法的参数
        //request.setAttribute("rqParam", requestBody);
        return true;

        /*JSONObject body = JSON.parseObject(request.getInputStream(),JSONObject.class);
        System.out.printf("body:%s\n",JSON.toJSONString(body));
        return true;*/
    }
}
